package com.whu.assignment8.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whu.assignment8.entity.Role;
import com.whu.assignment8.entity.User;
import com.whu.assignment8.mapper.RoleMapper;
import com.whu.assignment8.mapper.UserMapper;
import com.whu.assignment8.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Service
@Transactional
public class IUserServiceImpl extends ServiceImpl<UserMapper,User> implements IUserService {

    @Autowired
    PasswordEncoder passwordEncoder;

    @Resource
    UserMapper userMapper;

    @Resource
    RoleMapper roleMapper;

    @Value("${app.admin.user}")
    String adminUserName = "admin";

    @Value("${app.admin.password}")
    String adminPassword = "admin";

    @Transactional
    public void changePassword(String userName, String password) {
        userMapper.changePassword(userName,passwordEncoder.encode(password));
    }

    /**
     * 程序启动后，自动创建Admin角色和管理员账号
     */
    @Transactional
    @PostConstruct
    public void init(){
//        Optional<Role> roleAdmin = roleMapper.selectById("Admin");
//        Role role=roleAdmin.isPresent()? roleAdmin.get():null;
        Role role=roleMapper.selectById("Admin");
        if(role==null){
            role=new Role();
            role.setName("Admin");
            role.getAuthorities().add("Administration");
            roleMapper.insert(role);
        }

       User adminUser = userMapper.selectById(adminUserName);
        if(adminUser==null){
            User admin =new User();
            admin.setName(adminUserName);
            admin.setPassword(passwordEncoder.encode(adminPassword));
            admin.getRoles().add(role);
            userMapper.updateById(admin);
        }else{
            User admin=adminUser;
            if(!passwordEncoder.matches(adminPassword,admin.getPassword())){
                admin.setPassword(passwordEncoder.encode(adminPassword));
                userMapper.updateById(admin);
            }
        }
    }
}
